#!/bin/bash

# Redis Service Fix Script
# This script fixes the systemd service configuration for Redis

set -e

# Color definitions
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Logging functions
log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Check if running as root user
check_root() {
    if [[ $EUID -ne 0 ]]; then
        log_error "This script requires root privileges to run"
        exit 1
    fi
}

log_info "Redis Service Fix Script"
log_info "This script will fix the systemd service configuration"
log_info ""

# Check root
check_root

# Stop the service if it's running
log_info "Stopping redis service..."
systemctl stop redis 2>/dev/null || true
sleep 2

# Check if there are any redis processes
if pgrep -f redis-server >/dev/null; then
    log_warn "Redis process is still running, trying to kill it..."
    pkill -9 -f redis-server || true
    sleep 1
fi

# Create the fixed systemd service file
log_info "Creating fixed systemd service file..."
cat > /etc/systemd/system/redis.service << 'EOF'
[Unit]
Description=Redis persistent key-value database
After=network.target

[Service]
Type=forking
ExecStart=/opt/RadMedical/product/tool/redis/bin/redis-server /opt/RadMedical/product/tool/redis/etc/redis.conf
ExecStop=/bin/kill -s QUIT $MAINPID
PIDFile=/opt/RadMedical/product/tool/redis/log/redis.pid
TimeoutStopSec=5
Restart=always
RestartSec=10
User=redis
Group=redis
RuntimeDirectory=redis
RuntimeDirectoryMode=0755
UMask=007
PrivateTmp=yes
LimitNOFILE=65535

### Security hardening
NoNewPrivileges=true
RestrictRealtime=true
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX

[Install]
WantedBy=multi-user.target
EOF

log_info "Systemd service file created"

# Reload systemd
log_info "Reloading systemd daemon..."
systemctl daemon-reload

# Enable service
log_info "Enabling redis service..."
systemctl enable redis

# Start the service
log_info "Starting redis service..."
systemctl start redis

# Check service status
sleep 2
if systemctl is-active --quiet redis; then
    log_info "✓ Redis service started successfully!"
    
    # Test connection
    log_info "Testing Redis connection..."
    sleep 1
    if /opt/RadMedical/product/tool/redis/bin/redis-cli -a hmgsoft ping 2>/dev/null | grep -q "PONG"; then
        log_info "✓ Redis is responding correctly!"
    else
        log_warn "Redis service is running but connection test failed"
    fi
    
    log_info ""
    log_info "Service Status:"
    systemctl status redis --no-pager -l
else
    log_error "Redis service failed to start!"
    log_info "Checking logs..."
    journalctl -u redis -n 20 --no-pager
    exit 1
fi

log_info ""
log_info "=========================================="
log_info "Redis service fix completed!"
log_info "=========================================="

